<template>
  <div class="site-wrapper">
    <div class="header clearfix">
      <el-button size="small" type="primary" :disabled="isObserver" @click="createTask">新增</el-button>
      <el-button size="small" type="primary" :disabled="multipleSelection.length === 0 || isObserver" @click="delTask(false)">批量删除</el-button>
      <div class="filter" @click="showFilter = true;"><img src="../../../../assets/livolobim/filter.png" alt="">搜索</div>
      <div class="mask" v-if="showFilter" @click="showFilter = false;"></div>
      <div class="filter-wrapper" v-if="showFilter">
        <span class="filter-arrow"></span>
        <span class="filter-white"></span>
        <div class="filter-header">搜索</div>
        <el-form :model="form" style="padding: 0 16px;" label-width="70px">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="timeRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="录入人">
            <div class="select-btn" v-if="filterPeople.assigneeId">
              <span>{{filterPeople.assigneeName}}</span>
              <div class="del" @click="delMember(filterPeople)">移除</div>
            </div>
            <div v-if="!filterPeople.assigneeId" @click="selectDingUsers(filterPeople)" class="select-btn">请选择</div>
          </el-form-item>
          <el-form-item label="客户">
            <el-select
              style="width: 100%;"
              v-model="filterData.customerId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入客户名称、编号(最少输入2个字母)"
              :remote-method="remoteMethod"
              :loading="loading">
              <el-option
                v-for="item in custormerList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button style="float:right;margin-right: 16px;" size="small" type="primary" @click="searchItem(true)">确定</el-button>
          <el-button style="float:right;margin-right: 16px;" size="small" @click="resetFilter">重置</el-button>
        </div>
      </div>
    </div>
    <div class="data-wrapper">
      <el-table :height="tableHeight" :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55"></el-table-column>
        <el-table-column align="center" prop="customerName" label="客户" min-width="100"></el-table-column>
        <el-table-column align="center" prop="followPhaseName" label="跟进阶段" min-width="100"></el-table-column>
        <el-table-column align="center" prop="customerStatusName" label="客户状态" min-width="100"></el-table-column>
        <el-table-column align="center" prop="followResult" label="跟进内容" min-width="200"></el-table-column>
        <el-table-column align="center" prop="followDate" label="跟进时间" min-width="100"></el-table-column>
        <el-table-column label="操作" min-width="180" align="center">
          <template slot-scope="scope">
            <el-button @click="openEdit(scope.row, true)" type="text" size="small">查看</el-button>
            <el-button v-if="!isObserver" @click="openEdit(scope.row, false)" type="text" size="small">编辑</el-button>
            <el-button v-if="!isObserver" @click="delTask(scope.row.id)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style=""
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="page"
        :page-sizes="[15, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <el-dialog width="1000px" :visible.sync="showForm" :show-close="true">
        <div slot="title">
          <h2 style="text-align:center;margin-bottom:0;">{{form.id? isCheck? '查看': '编辑': '创建'}}跟进</h2>
        </div>
        <div class="form-wrapper" style="padding: 0 20px;">
          <el-form ref="form" :model="form" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="客户：">
                  <span slot="label">客户<span style="color: red;">*</span>：</span>
                  <el-select
                    style="width: 100%;"
                    v-model="form.customerId"
                    filterable
                    remote
                    @change="getOrderList"
                    :disabled="isCheck"
                    reserve-keyword
                    placeholder="请输入客户名称、编号(最少输入2个字母)"
                    :remote-method="remoteMethod"
                    :loading="loading">
                    <el-option
                      v-for="item in custormerList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="跟进时间：">
                  <span slot="label">跟进时间<span style="color: red;">*</span>：</span>
                  <el-date-picker :disabled="isCheck" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="form.followDate" style="width: 100%;"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="跟进阶段：">
                  <span slot="label">跟进阶段<span style="color: red;">*</span>：</span>
                  <el-select :disabled="isCheck" style="width: 100%;" v-model="form.followPhase" placeholder="请选择跟进阶段">
                    <el-option v-for="item in gjzt" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="客户状态：">
                  <span slot="label">客户状态<span style="color: red;">*</span>：</span>
                  <el-select :disabled="isCheck" style="width: 100%;" v-model="form.customerStatus" placeholder="请选择客户状态">
                    <el-option v-for="item in khzt" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="订单号：">
                  <el-select clearable :disabled="isCheck" style="width: 100%;" v-model="form.orderNo" placeholder="请选择订单号">
                    <el-option v-for="item in orderList" :key="item.orderNo" :label="item.orderNo + ' | ' + item.owner + ' | ' + item.quoteDate" :value="item.orderNo"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col v-if="form.id" :span="12">
                <el-form-item style="font-weight: bold;" label="跟进人：">
                  <el-input disabled :value="form.createUserName"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item style="font-weight: bold;" label="跟进结果：">
                  <span slot="label">跟进结果<span style="color: red;">*</span>：</span>
                  <el-input :disabled="isCheck" type="textarea" :rows="3" placeholder="请输入任务内容" v-model="form.followResult"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button style="float:right;" size="small" @click="showForm = false">关闭</el-button>
              <el-button v-if="!isCheck" style="float:right;margin-right: 10px;" size="small" type="primary" @click="saveForm">保存</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import dingMixin from "@/mixins/ding";
import formUtil from "@/utils/formUtil";
import {dateUtil} from '@/utils/dateUtil'

export default {
  data() {
    return {
      showPeopleBtn: false,
      showFilter: false,
      loading:false,
      showForm: false,
      tableHeight: window.tableHeight,
      tableData: [],
      page:1,
      pageSize: 15,
      totalPage: 1,
      form: {
        customerNo: '',
        customerName: '',
        customerId: '',
        followResult: '',
        followDate: '',
        followPhase: '',
        content: '',
        orderNo: ''
      },
      formVerify: {
        customerId: '请输入客户名称',
        followResult: '请输入跟进结果',
        followPhase: '请选择跟进阶段',
        followDate: '请输入跟进日期',
        customerStatus: '请选择客户状态'
      },
      custormerList: [],
      filterData: {
        createUser: '',
        customerId: ''
      },
      gjzt: [],
      khzt: [],
      multipleSelection: [],
      filterPeople:{
        assigneeId: '',
        assigneeName: '',
      },
      isCheck: false,
      allDict: [],
      timeRange: ['', ''],
      orderList: []
    }
  },
  mixins: [dingMixin],
  computed: {
    isObserver() {
      return this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1289086254290432001')
    }
  },
  async mounted() {
    this.$nextTick(() => {
      this.tableHeight = document.documentElement['clientHeight'] - 170;
    })
    window.onresize = () => {
      this.tableHeight = document.documentElement['clientHeight'] - 170
    }
    this.searchItem(true);
    this.gjzt = await this.getDict('1291997498622431234')
    this.khzt = await this.getDict('1291997539810496513')
  },
  methods: {
    async getOrderList(val) {
      this.orderList = await this.$httpN.postQ('crm/order/customerOrders', {customerId: val});
    },
    async getDict(pid) {
      if(this.allDict.length === 0) this.allDict = await this.$httpN.postQ('crm/dict/list');
      return this.allDict.filter(item => item.pid === pid);
    },
    resetFilter() {
      this.filterData = {
        createUser: '',
        customerId: ''
      };
      this.timeRange = ['', ''];
      formUtil.resetData(this.filterPeople);
    },
    selectDingUsers(target) {
      this.complexPicker(1, [], []).then(
        data => {
          target.assigneeId = data[0].emplId;
          target.assigneeName = data[0].name;
        }
      );
    },
    delMember(target) {
      target.assigneeId = '';
      target.assigneeName = '';
    },
    createTask() {
      this.showForm = true;
      this.isCheck = false;
      formUtil.resetData(this.form);
    },
    delTask(id) {
      let ids = id ? [id]: this.multipleSelection.map(item => item.id);
      formUtil.submitConfirm('您确定要删除跟进吗？', async ()=> {
        if(!await this.$httpN.postB('crm/customerfollow/delete', ids, false)) return;
        formUtil.submitSuccess('删除成功');
        this.searchItem(true);
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async openEdit(target, isCheck) {
      let newForm = formUtil.deepCopy(target);
      this.form = newForm;
      if(this.form.customerName) this.custormerList = [{name: this.form.customerName, id: this.form.customerId, code: this.form.customerNo}];
      if(this.form.orderNo) this.getOrderList(this.form.orderNo);
      this.showForm = true;
      this.isCheck = isCheck;
    },
    async saveForm() {
      this.custormerList.forEach((item) => {
        if(item.id === this.form.customerId) {
          this.form.customerName = item.name;
          this.form.customerNo = item.code;
        }
      })
      if(!formUtil.verifyData(this.form, this.formVerify)) return;
      if(!await this.$httpN.postB('crm/customerfollow/save', this.form)) return;
      formUtil.submitSuccess('成功');
      this.showForm = false;
      this.searchItem(true);
    },
    async remoteMethod(query) {
      if (query !== '' && query.length >= 2) {
        this.loading = true;
        this.custormerList = await this.$httpN.postQ('mpb/customer/getByName', {name: query});
        this.loading = false;
      } else {
        this.custormerList = [];
      }
    },
    sizeChangeHandle(limit) {
      this.pageSize = limit;
      this.searchItem(true);
    },
    currentChangeHandle(page) {
      this.page = page;
      this.searchItem();
    },
    async searchItem(init) {
      if(init) this.page = 1;
      let data = await this.$httpN.postB('crm/customerfollow/list',{
        createUser: this.filterPeople.assigneeId,
        beginTime: this.timeRange[0]? this.timeRange[0] + ' 00:00:00' : '',
        endTime: this.timeRange[1]? this.timeRange[1] + ' 23:59:59': '',
        customerId: this.filterData.customerId,
        page: this.page,
        limit: this.pageSize,
      })
      this.tableData = data.list;
      this.totalPage = data.totalCount
    }
  }
}
</script>

<style lang="scss" scoped>
  .header{
    position: relative;
    padding: 10px 0 0 20px ;
    .filter{
      cursor: pointer;
      float: right;
      margin-right: 30px;
      line-height: 30px;
      img{
        width: 16px;
        margin-right: 3px;
      }
    }
    .mask{
      position: fixed;
      height: 100vh;
      width: 100%;
      top: 0;
      right: 0;
      z-index: 3;
    }
    .filter-wrapper{
      position: absolute;
      width: 455px;
      padding-bottom: 20px;
      background: white;
      top: 48px;
      right: 20px;
      z-index: 99;
      border-radius: 5px;
      box-shadow: 0 0 3px black;
      .filter-header{
        line-height: 40px;
        padding-left: 16px;
        border-bottom: 1px solid #DDD;
        margin-bottom: 20px;
      }
      .filter-arrow{
        width:12px;
        height:12px;
        position: absolute;
        top: -7px;
        right: 20px;
        box-shadow: 0 0 3px black;
        transform: rotate(45deg);
      }
      .filter-white{
        width:18px;
        height:18px;
        position: absolute;
        top: -2px;
        right: 17px;
        border-radius: 3px;
        background: white;
      }
    }
  }
  .data-wrapper{
    padding: 0 20px;
    margin-top: 10px;
  }
  .select-btn{
    display: inline-block;
    font-weight: normal;
    margin-right: 5px;
    width: 80px;
    height: 28px;
    border-radius: 30px;
    background: #FAFAFA;
    border: 1px solid #ECECEC;
    position: relative;
    line-height: 28px;
    color: #7982A7;
    font-size: 12px;
    text-align: center;
    position: relative;
    cursor: pointer;
    .del{
      position: absolute;
      top:0;
      left: 0;
      width: 100%;
      height: 100%;
      border-radius: 30px;
      color: white;
      text-align: center;
      background:rgba(130, 130, 130, 0.9);
      display: none;
    }
    &:hover{
      .del{
        display: block;
      }
    }
  }
  .fileitem{
    line-height: 32px;
    margin-bottom: 5px;
    background: #F5F5F5;
    width: 474px;
    padding-left:15px;
    font-size: 12px;
    .uploadtip{
      float:right;
      margin-right: 20px;
      cursor: pointer;
    }
  }
  .addfilebtn{
    cursor: pointer;
    color: #909399;
    display: block;
    font-weight: normal;
  }
</style>